<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '发布约会',
  },
}
</route>

<template>
  <view style="position: relative;">
    <!-- 生成分享图 -->
    <view style="visibility: hidden;position: absolute;left: 0;top: 0;pointer-events: none;">
      <l-painter ref="painter" v-if="imgData.url">
        <l-painter-view css="display: inline-block; width: 750rpx;position: relative;">
          <l-painter-image
            :src="imgData.url"
            css="width: 750rpx; height: 600rpx; object-fit: cover; background: #f5f5f5" 
          />
          <l-painter-view
            css="background: rgba(0,0,0,0.5); width: 750rpx; position: absolute; left: 0; bottom: 0; padding: 12rpx; box-sizing: border-box;"
          >
            <l-painter-text 
              css="color: #fff; font-size: 32rpx;" 
              :text="imgData.text" 
            />
          </l-painter-view>
        </l-painter-view>
      </l-painter>
    </view>
    <!-- 走马灯 -->
    <view class="w-750rpx m-a" v-if="isShowTips">
      <wd-notice-bar 
        text="在了解对方之前，不要透露过多个人信息，包括地址、电话号码等敏感信息。任何要求提供验证码或借钱的行为都可能是骗局，务必保持警惕‌。不去私密和不安全的约会场所，注意自身财产和人身安全，发生任何安全事故，责任自负。"
        :color="themeConfig.theme === 'dark' ? '#fff': '#1B1116'"
        background-color="rgba(255, 255, 255, 0)"
      >
        <template #prefix>
          <view class="w-32rpx h-32rpx font-size-0 pr-16rpx">
            <wd-img 
              width="100%" 
              height="100%" 
              :src="tips" 
              mode="aspectFill" 
            />
          </view>
        </template>
      </wd-notice-bar>
    </view>
    <wd-form ref="formRefs" :model="formData" :errorType="errorType">
      <!-- <wd-input 
        align-right 
        type="number" 
        label="约会金额" 
        prop="payMoney"
        v-model="formData.payMoney" 
        placeholder="请输入" 
        :rules="[{ required: true, message: '请输入约会金额！' }]"
      />
      <view class="border-1px"></view> -->
      
      <wd-picker 
        align-right 
        :columns="useCommon.commonState.dictInfo['dateType']" 
        label="约会类型" 
        v-model="formData.datingType" 
        prop="datingType"
        :rules="[{ required: true, message: '请选择约会类型！' }]"
      />
      <view class="border-1px"></view>

      <wd-datetime-picker 
        label="约会开始时间" 
        align-right 
        prop="startTime"
        v-model="formData.startTime" 
        :rules="[{ required: true, message: '请选择开始时间！' }]"
      />
      <view class="border-1px"></view>

      <wd-datetime-picker 
        label="约会结束时间" 
        align-right 
        prop="endTime"
        v-model="formData.endTime" 
        :rules="[{ required: true, message: '请选择结束时间！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-cell 
        title="约会区域" 
        required 
        :value="city ? city : '请选择'" 
        :custom-value-class="city ? '' : 'cell-placeholder'"
        is-link 
        :to="`/feature/areaPicker?isAll=1&isRequired=2&areaStr=${[formData.provinceId,formData.cityId,formData.districtId].filter(item => !!item).join(',')}`"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <wd-input 
        align-right 
        type="text" 
        label="详细地址" 
        prop="location"
        v-model="formData.location" 
        placeholder="请输入" 
        :rules="[{ required: true, message: '请输入详细地址！' }]"
      />
      <view class="border-1px"></view>

      <wd-cell 
        title="是否置顶(1元/天)" 
        required 
        custom-class="switch-cell"
      >
        <view class="h-48rpx flex flex-items-center flex-justify-end">
          <wd-switch v-model="formData.topFlag" size="32rpx" />
        </view>
      </wd-cell>
      <view class="border-1px"></view>
      
      <wd-input 
        align-right 
        type="text" 
        label="约会主题" 
        prop="location"
        v-model="formData.datingTheme" 
        placeholder="请输入" 
        :rules="[{ required: true, message: '请输入约会主题！' }]"
      />
      <view class="border-1px"></view>
      
      <view class="w-750rpx m-a bg-white box-border"
        :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
      >
        <view class="w-center flex-sb-center font-size-24rpx pt-16rpx">
          <view class="h-full flex-a-center font-size-14px">
            <!-- <text class="font-size-18px color-#fa4350 mr-4rpx">*</text> -->
            约会内容
          </view>
        </view>
        <wd-textarea 
          placeholderStyle="font-size: 24rpx" 
          v-model="formData.content" 
          placeholder="请输入" 
          prop="content"
          :rules="[{ required: false, message: '请输入约会内容！' }]"
        />
        <view class="border-1px"></view>
      </view>
      
      <view class="w-750rpx m-a bg-white box-border"
        :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
      >
        <view class="w-center flex-sb-center font-size-24rpx pt-32rpx">
          <view class="h-full flex-a-center font-size-14px">
            <!-- <text class="font-size-18px color-#fa4350 mr-4rpx">*</text> -->
            约会图片
          </view>
        </view>
        <view class="w-center pt-32rpx">
          <wd-upload 
            :file-list="formData.fileList" 
            image-mode="aspectFill" 
            :action="VITE_UPLOAD_BASEURL" 
            :limit="3"
            @change="handleUploadChange"
            @fail="handleUploadFail"
          ></wd-upload>
        </view>
        <view class="border-1px"></view>
      </view>
    </wd-form>

    <!-- 发布按钮 -->
    <view class="btn-full w-center pt-40rpx">
      <wd-button 
        class="btn-w-full btn-h-78"
        :loading="loading"
        @click="submit"
      >发布</wd-button>
    </view>

    <view class="h-50rpx"></view>
    
    <wd-action-sheet 
      v-model="showPaySheet" 
      :actions="getActions" 
      cancel-text="取消"
      :title="`发布本次约会信息需消耗${payMoney}个乐缘币`"
      @select="selectPayMethod"
    />
    
    <wd-message-box selector="wd-message-box-slot">
      <view class="">
        <view class="align-l">1、发起约会者和应约者需完善个人资料并实名认证。</view>
        <view class="align-l">2、约会广场为1对1应约模式，发起约会者可在应约者中匹配1名心仪之人“接受邀约”。</view>
        <view class="align-l">3、发起约会者与应约者匹配成功，“接受邀约”后，本次约会成功。</view>
        <view class="align-l">4、截止约会开始前，如发起约会者在应约者中没有匹配到心仪的人，本次约会将自动失效。</view>
        <view class="align-l">5、约会双方对本次约会的安全全权负责。</view>
      </view>
    </wd-message-box>
  </view>
</template>
  
<script lang="ts" setup>
import LPainter from "@/components/lime-painter/components/l-painter/l-painter.vue";
import LPainterView from "@/components/lime-painter/components/l-painter-view/l-painter-view.vue";
import LPainterImage from "@/components/lime-painter/components/l-painter-image/l-painter-image.vue";
import LPainterText from "@/components/lime-painter/components/l-painter-text/l-painter-text.vue";
import { useCommonStore, useThemeStore, useUserStore } from "@/store";
import { comUploadFile, formatDate, getActions } from "@/utils";
import { useMessage, useToast } from "wot-design-uni";
import { AddDatingInfo } from "@/service/db_love";
import { GetDefaultAmountConfigQueryCode } from "@/service/db_index";
import { Main } from "@/service/types";
import { tips } from "@/static/base64";

// 主题颜色
const { themeConfig } = useThemeStore();
const useCommon = useCommonStore();
const user = useUserStore();
const toast = useToast();

// 显示支付方式
const showPaySheet = ref(false);

const formData = reactive({
  datingTheme: '',
  datingType: '',
  content: '',
  startTime: +new Date(),
  endTime: +new Date() + 86400000,
  provinceId: '',
  cityId: '',
  districtId: '',
  location: '',
  topFlag: true,
  fileList: [],
  sharePhotoId: '',
})

const formRefs = ref();
const errorType = ref<"message" | "toast" | "none">('toast');
const ruleMsg = useMessage('wd-message-box-slot');
const submit = () => {
  if (!user.getUseVo.userProfileInfoVo.nickname) {
    setTimeout(() => {
      uni.navigateTo({ url: '/activity/info' });
    }, 1000)
    return toast.show('请先完善个人资料');
  }
  if (!user.activityInfo.id) {
    toast.show('请先填写资料');
    setTimeout(() => {
      uni.navigateTo({ url: '/activity/addActivityInfo' })
    }, 1000)
    return
  }
  handleValidate();
}

const handleValidate = () => {
  formRefs.value
    .validate()
    .then(({ valid }) => {
      if (!valid) return;
      const _startTime = +new Date(formData.startTime);
      const _endTime = +new Date(formData.endTime);
      if (_startTime > _endTime) return toast.show('开始时间不能大于结束时间！');
      if (!formData.provinceId) return toast.show('请选择约会区域！');
      // if (!fileList.value.length) {
      //   return toast.show('请上传约会图片！');
      // }
      handleSumbit();
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

const handleSumbit = async () => {
  uni.showLoading({
    title:'正在生成分享图片...',
  })
  try {
    await getImgData();
  } catch (error) {
    console.log(error);
  }
  uni.hideLoading();
  const imageIds = fileList.value.map((item) => {
    const res = item.response ? JSON.parse(item.response) : {};
    const data = res.data || {};
    return data.id
  }).join(',');

  const _amount = joinMoney.value + topAmount.value;
  payMoney.value = formData.topFlag ? parseFloat((_amount).toFixed(2)) : joinMoney.value;
  const data = {
    ...formData,
    fileList: undefined,
    datingType: formData.datingType,
    content: formData.content,
    startTime: formatDate(new Date(formData.startTime)),
    endTime: formatDate(new Date(formData.endTime)),
    imageIds,
  }
  submitConfirm(data);
}

const loading = ref(false);
// 新增约会
const addDatingInfo = async (data) => {
  try {
    loading.value = true;
    const res = await AddDatingInfo(data);
    loading.value = false;
    if (res.code == '6000012') {
      // useCommon.paymentMsgConfirm({
      //   userId: user.userInfo.id,
      //   type: data.topFlag ? 'create_dating_top' : 'create_dating',
      //   relatedBusinessInfo: JSON.stringify(data),
      // }, () => {
      //   // 充值成功
      //   toast.show('发布成功！');
      //   setTimeout(() => { uni.navigateBack() }, 1000);
      // }, false, message)
      return 
    }
    if (res.code == 200) {
      toast.show('发布成功！');
      setTimeout(() => { uni.navigateBack() }, 1000);
    }
  } catch (error) {
    console.log(error)
    loading.value = false;
  }
}

// 上传文件相关
const fileList = ref([]);
const handleUploadChange = ({ fileList: files }) => {
  fileList.value = files;
}
const handleUploadFail = ({ error }) => {
  const res = error.data ? JSON.parse(error.data) : {};
  if (res.status == 403) {
    user.clearUserInfo();
    // 403错误  -> 清理用户信息，跳转到登录页
    uni.navigateTo({ url: '/pages/login/index' })
  }
}

const joinMoney = ref(0);
// 约会需要的金额
const getDefaultAmountConfigQueryCode = async () => {
  try {
    const res = await GetDefaultAmountConfigQueryCode({
      code: 'create_dating'
    })
    const data = res.data || {} as Main.DefaultAmountConfigQueryCode;
    joinMoney.value = data.amount || 0;
  } catch (error) {
    console.log(error);
  }
}

const topAmount = ref(0);
// 获取置顶每天的费用
const getTopAmount = async () => {
  try {
    const res = await GetDefaultAmountConfigQueryCode({
      code: 'top_dating'
    })
    const data = res.data || {} as Main.DefaultAmountConfigQueryCode;
    topAmount.value = data.amount || 0;
  } catch (error) {
    console.log(error);
  }
}

const message = useMessage();
const payMoney = ref(0);
const submitData = ref({} as any);
const submitConfirm = (data) => {
  // if (!user.getUseVo.userProfileInfoVo.nickname) {
  //   setTimeout(() => {
  //     uni.navigateTo({ url: '/activity/info' });
  //   }, 1000)
  //   return toast.show('请先完善个人资料');
  // }

  const list: Main.CheckInfoItem[] = [
    {
      checkType: 'msg',
      content: data.datingTheme,
    },
    {
      checkType: 'msg',
      content: data.content,
    },
    {
      checkType: 'msg',
      content: data.location,
    },
  ];
  
  fileList.value.forEach(item => {
    const res = item.response ? JSON.parse(item.response) : {};
    const _data = res.data || {};
    list.push({
      checkType: 'img',
      content: _data.preUrl,
      mediaType: 2
    })
  });

  useCommon.secCheck({
    userId: user.userInfo.id,
    checkInfoList: list
  }, (resData) => {
    submitData.value = data;
    showPaySheet.value = true;
  })
  // message
  //   .confirm({
  //     msg: `将会消耗${data.payMoney}的乐缘币, 是否继续？`,
  //     title: '发布约会'
  //   })
  //   .then(() => {
  //     addDatingInfo(data);
  //   })
  //   .catch(() => {
  //     console.log('点击了取消按钮')
  //   })
}

// 选择支付方式
const selectPayMethod = (options) => {
  const { item } = options || {};
  submitData.value.userId = user.userInfo.id;
  if (item.type === 'wechat') {
    useCommon.reduceMoney({
      userId: user.userInfo.id,
      type: submitData.value.topFlag ? 'create_dating_top' : 'create_dating',
      relatedBusinessInfo: JSON.stringify(submitData.value),
      amount: payMoney.value,
    }, () => {
      // 充值成功
      toast.show('发布成功！');
      setTimeout(() => { uni.navigateBack() }, 1000);
    })
  } else {
    addDatingInfo(submitData.value);
  }
}

const city = ref('');
// 更新城市
function handleUpdateArea(data) {
  if (!data) {
    city.value = '';
    Object.assign(formData, {
      provinceId: undefined, 
      cityId: undefined, 
      districtId: undefined
    })
    return
  }
  
  const [valStr, labelStr] = data.split('/');
  const [provinceVal, cityVal, districtVal] = valStr.split(',');
  const labelList = labelStr.split(',');
  
  // 如果地区名称重复, 只留一个
  if (labelList[0] === labelList[1]) {
    labelList.shift();
  }
  city.value = labelList.join('');
  Object.assign(formData, {
    provinceId: provinceVal, 
    cityId: cityVal, 
    districtId: districtVal
  })
}


// base64转换临时路径
function base64ToTempPath(base64Data) {
  const fs = uni.getFileSystemManager()
  const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.jpg`
  fs.writeFileSync(tempFilePath, base64Data, 'base64')
  return tempFilePath
}

const imgData = ref<any>({});
const painter = ref();
const getImgData = () => {
  return new Promise<void>((resolve, reject) => {
    const _startTime = formatDate(new Date(formData.startTime));
    const _endTime = formatDate(new Date(formData.endTime));

    const fileInfoVoList = fileList.value.map((item) => {
      const res = item.response ? JSON.parse(item.response) : {};
      const data = res.data || {};
      return data;
    });
    const firstItem: any = fileInfoVoList && fileInfoVoList.length ? fileInfoVoList[0] : {};
    if (!firstItem.preUrl) return reject();

    imgData.value = {
      url: firstItem.preUrl || '',
      text: `约会主题: ${formData.datingTheme}\n约会开始时间: ${_startTime}\n约会结束时间: ${_endTime}\n约会区域: ${city.value}\n详细地址: ${formData.location}`,
      res: '',
    }

    setTimeout(() => {
      painter.value.canvasToTempFilePathSync({
        fileType: 'jpg',
        quality: 0.2,
        success: async (res) => {
          try {
            let tempPath = res.tempFilePath;
            // #ifdef MP-WEIXIN
            const pureBase64 = res.tempFilePath.replace(/^data:image\/\w+;base64,/, '');
            tempPath = base64ToTempPath(pureBase64);
            // #endif

            // 上传图片
            const _res = await comUploadFile({
              url: '/file-info',
              tempFilePath: tempPath,
              formData: {}
            })
            if (_res.code != 200) {
              toast.show(res.message);
              reject();
              return;
            }
            formData.sharePhotoId = _res.data.id;
            resolve();
          } catch (error) {
            console.log('err => comUploadFile', error);
            reject();
          }
        },
        fail(e) {
          console.log('err', e);
          reject();
        }
      })
    }, 500)
  })
}

const isShowTips = ref(false);
onHide(() => {
  isShowTips.value = false;
})

onLoad((options) => {
  uni.$on('updateArea', handleUpdateArea);
  
  nextTick(() => {
    ruleMsg
      .alert({
        title: '约会须知'
      })
      .then(() => {})
      .catch(() => {
        console.log('点击了取消按钮')
      })
  })
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$off('updateArea', handleUpdateArea);
})

onShow(() => {
  isShowTips.value = true;
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '发布约会';
  })

  getDefaultAmountConfigQueryCode();
  getTopAmount();
})
</script>

<style lang="scss" scoped>
.align-l {
  text-align: left;
}
:deep(.uni-textarea-textarea) {
  font-size: 24rpx !important;
}
:deep(.wd-input) {
  padding-right: 84rpx !important;
}
:deep(.wd-notice-bar) {
  padding-right: 0 !important;
}
:deep(.switch-cell .wd-cell__left) {
  flex: 2 !important;
}
</style>
      